import { messages } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Form, Input, Button, message, Row, Col, DatePicker, InputNumber, Select, Table, Affix, Modal, Spin, Switch } from 'antd'
const Option = Select.Option;
const FormItem = Form.Item;
const { TextArea } = Input;
import mileageExpenseService from 'containers/mileage-subsidy-expense/mileage-subsidy-expense.service'
import moment from 'moment'
import menuRoute from 'routes/menuRoute'
import Location from 'components/location'
import ImageUpload from 'components/image-upload'
import Chooser from 'components/chooser'
import 'styles/mileage-subsidy-expense/new-mileage-cost.scss'
import common  from'containers/financial-management/check-center/check-common'
import invoiceImg from 'images/expense/invoice-info.png'

class EditMileageCost extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      record: null,
      tableLoading: false,
      pageLoading: false,
      date: '',
      type: 'new',
      currencyList: [],
      isInvoice: 0, //生成费用标识
      data: [],
      totalSubsidy: 0,
      totalMileage: 0,
      referenceAmount: 0,
      referenceMileage: 0,
      currency: 'CNY',
      steps: [],
      priceList: [],
      remark: '',
      invoiceOID: '',
      display: 'none',
      expense: {},
      columns: [
        {
          title: messages('mileage-subsidy-expense.key1'/*出发信息*/),
          dataIndex: 'start',
          width: '25%',
          render: (record, index) => {
            return <div>
              <div>{moment(index.departTime).format('YYYY-MM-DD HH:mm')}</div>
              <div>{record.place}</div>
            </div>
          }
        },
        {
          title: messages('mileage-subsidy-expense.key2'/*到达信息*/),
          dataIndex: 'end',
          width: '25%',
          render: (record, index) => {
            return <div>
              <div>{moment(index.arriveTime).format('YYYY-MM-DD HH:mm')}</div>
              <div style={{ overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{record.place}</div>
            </div>
          }
        },
        {
          title: messages('mileage-subsidy-expense.key3'/*里程*/),
          dataIndex: 'mileage',
          width: '15%',
          render: (record, index) => {
            return <div>
              <div>{messages('mileage-subsidy-expense.key4'/*实际*/)}:{record}</div>
              <div>{messages('mileage-subsidy-expense.key5'/*参考*/)}:{index.referenceMileage}</div>
            </div>
          }
        },
        {
          title: messages('mileage-subsidy-expense.key6'/*事由说明*/),
          dataIndex: 'remark'
        }
      ],
      mileageExpenseList: menuRoute.getRouteItem('mileage-subsidy-expense','key'),
      visible: false
    }
  }


  componentWillMount(){
    const { company } = this.props;
    this.setState({
      date: this.props.location.state.date,
      pageLoading: true,
      invoiceOID: this.props.location.state.invoiceOID,
      currencyList: [{ currency: company.baseCurrency, currencyName: company.baseCurrency }]
    },() => {
      // this.getCost(this.state.date)
      this.getOrders(this.state.date, this.state.isInvoice);
      this.getFeeDetail()
    });
  }

  //编辑费用里程补贴详情
  getFeeDetail = ()=>{
    const { invoiceOID } = this.state;
    mileageExpenseService.getFeeDetail(invoiceOID).then(res => {
      if(res.data.mileageAllowanceExpenseDTO.steps.length > 1){
        res.data.mileageAllowanceExpenseDTO.steps[res.data.mileageAllowanceExpenseDTO.steps.length - 1].endUnit = '以上'
      }
      this.setState({
        pageLoading: false,
        expense: res.data,
        totalSubsidy: res.data.originalAmount || 0,
        totalMileage: res.data.mileageAllowanceExpenseDTO.mileage || 0,
        referenceAmount: res.data.mileageAllowanceExpenseDTO.referenceAmount || 0,
        referenceMileage: res.data.mileageAllowanceExpenseDTO.referenceMileage || 0,
        currency: res.data.mileageAllowanceExpenseDTO.currency || 'CNY',
        steps: res.data.mileageAllowanceExpenseDTO.steps,
        priceList: res.data.mileageAllowanceExpenseDTO.priceList
      })
    })
  };

  onCancel = () =>{
    this.setState({ visible:false })
  };

  goBack = () => {
    this.context.router.push(this.state.mileageExpenseList.url)
  };

  //新建编辑费用
  handleNew = e => {
    e.preventDefault();
    const { date } = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if(!err){
        this.controlPrice(values.amount).then(() => {
          values.currency = values.currencyCode;
          values.date = moment(date).format('YYYY-MM');
          values.createdTime = moment(new Date()).format('YYYY-MM-DD');
          values.amount = values.amount.toString();
          this.deleteObjectAttribute(
            values,
            ['totalMileage', 'referenceMileage', 'totalSubsidy', 'amountInfo', 'mileageDetail', 'currencyCode', 'type']
          )
        })
      }
    })
  };

  //删除对象属性
  deleteObjectAttribute(obj, values){
    values.map(item => {
      delete obj[item]
    })
  }

  getTwoDecimal = num =>{
    return (Math.round(num * 10) / 10)
  }

  //获取订单
  getOrders(date, invoice) {
    this.setState({ tableLoading:true });
    mileageExpenseService.getOrders(date, invoice).then(response => {
      this.setState({
        tableLoading: false,
        data: response.data.orders
      })
    })
  }

  handleMouseOver = e => {
    this.setState({ display:'block' })
  };

  handleMouseOut = e => {
    this.setState({ display:'none' })
  };

  handleRowClick = record => {
    this.setState({ record:record, visible:true })
  };

  handleChangeExpenseApportion = expenseApportion => {
    this.setState({ expenseApportion })
  };

  getFieldValue = (type, value, name) => {
    if(type === 'DATETIME' || type === 'DATE')
      return value ? moment(value) : null;
    if(type === 'LONG' || type === 'DOUBLE')
      return Number(value);
    if(type === 'PARTICIPANTS'){
      let { user } = this.props;
      return value ? JSON.parse(value) :[user];
    }
    else
      return value;
  };

  switchField = (field) => {
    switch (field.fieldType) {
      case 'LONG':
        return <InputNumber style={{width: '100%'}} precision={0} disabled={!field.editable}/>;
      case 'DOUBLE':
        return <InputNumber style={{width: '100%'}} disabled={!field.editable}/>;
      case 'TEXT':
        if (field.customEnumerationOID) {
          return field.list ? (
            <Select>
              {field.list.map(item => <Option key={item.value} value={item.value}>{item.messageKey}</Option>)}
            </Select>
          ) : <Spin/>
        } else {
          return <Input/>
        }
      case 'DATE':
        return <DatePicker disabled={!field.editable}/>;
      case 'DATETIME':
        return <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" disabled={!field.editable}/>;
      case 'GPS':
        return <Location disabled={!field.editable}/>;
      case 'LOCATION':
        return <Input disabled={!field.editable}/>;
      case 'PARTICIPANTS':
        return <Chooser disabled={!field.editable}
                        type="participants"
                        newline
                        labelKey="fullName"
                        valueKey="userOID"
                        listExtraParams={{ formOID: '' }}/>
    }
  }

  render() {
    const { currencyList, columns ,tableLoading, pageLoading, data, visible, record, totalSubsidy, totalMileage,
      referenceMileage, currency, remark, steps, priceList, display, expense, referenceAmount } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 16}
    };
    return (
      <div className='new-mileage-cost'>
        <Spin spinning={pageLoading}>
          <h3 className='bottom-line'>查看费用（不可编辑）</h3>
          <Form style={{marginBottom:'60px'}} onSubmit={this.handleNew}>
            <FormItem {...formItemLayout} label={messages('mileage-subsidy-expense.key7'/*类型*/)}>
              {getFieldDecorator('type',)(
                <span>里程补贴</span>
              )}
            </FormItem>

            {expense.data && expense.data.sort((o,u) => o.sequence - u.sequence).map(item => item.showOnList && (
              <div key={item.fieldOID}>
              <FormItem {...formItemLayout} label={item.name}>
              <Row>
                <Col span={10}>
                  <FormItem >
                {getFieldDecorator(item.messageKey, {
                  initialValue:this.getFieldValue(item.fieldType, item.value, item.defaultValueName)
                })(
                  this.switchField(item)
                )}
                  </FormItem>
                </Col>
              </Row>
              </FormItem>
              </div>
            ))}
            <FormItem {...formItemLayout} label={messages('mileage-subsidy-expense.key8'/*金额*/)}>
              {getFieldDecorator('amountInfo',)(
                <Row>
                  <Col span={10}>
                    <FormItem>
                      {getFieldDecorator('currencyCode',{
                        rules: [{
                          required: true,
                          message: messages('mileage-subsidy-expense.key9'/*请选择币种*/)
                        }],
                        initialValue: currency ? currency : ''
                      })(
                        <Select disabled optionLabelProp='value' dropdownMatchSelectWidth={false}
                                placeholder={messages('common.please.select')/* 请选择 */}>
                          {currencyList.map(item => {
                            return <Option key={item.currency}>{item.currencyName}</Option>
                          })}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={1}/>
                  <Col span={13}>
                    <FormItem>
                      {getFieldDecorator('amount',
                        {
                          rules:[{
                            required: true,
                            message: messages('mileage-subsidy-expense.key10'/*请输入合法的金额(小数点最多两位)*/)
                          }],
                          initialValue: totalSubsidy ? totalSubsidy : ''
                        })(
                        <InputNumber style={{width: '100%'}} min={0} precision={2} />
                      )}
                    </FormItem>
                  </Col>
                </Row>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="公司支付">
              {getFieldDecorator('payByCompany', {
                valuePropName: 'checked',
                initialValue: expense.payByCompany
              })(
                <Switch />
              )}
            </FormItem>
            {expense.withReceipt && expense.expenseTypeOID && <FormItem {...formItemLayout} label="替票">
              {getFieldDecorator('invoiceInstead', {
                valuePropName: 'checked',
                initialValue: expense.invoiceInstead
              })(
                <Switch />
              )}
            </FormItem>}
            <FormItem {...formItemLayout} label="录入发票">
              {getFieldDecorator('vatInvoice', {
                valuePropName: 'checked',
                initialValue: expense.vatInvoice
              })(
                <Switch />
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="附件">
              <ImageUpload defaultFileList={expense.attachments}
                           attachmentType="INVOICE_IMAGES"
                           onChange={this.uploadSuccess}
                           maxNum={3}
                           isShowDefault={true}/>
            </FormItem>

            <FormItem {...formItemLayout} label={messages('mileage-subsidy-expense.key11'/*累计里程*/)}>
              <Row>
                <Col span={10}>
                  <FormItem>
                    {getFieldDecorator('totalMileage', {
                      initialValue: this.getTwoDecimal(totalMileage)
                    })(
                      <span>{this.getTwoDecimal(totalMileage)}</span>
                    )}
                  </FormItem>
                </Col>
                <Col span={1}/>
                <Col span={13}>
                  <FormItem {...formItemLayout} label={messages('mileage-subsidy-expense.key12'/*参考里程(KM)*/)}>
                    {getFieldDecorator('referenceMileage', {
                      initialValue: this.getTwoDecimal(referenceMileage)
                    })(
                      <span>{this.getTwoDecimal(referenceMileage)}</span>
                    )}
                  </FormItem>
                </Col>
              </Row>
            </FormItem>
            <FormItem {...formItemLayout}  label={messages('mileage-subsidy-expense.key13'/*补贴总额*/)}>
              {getFieldDecorator('totalSubsidy', {
                initialValue: common.formatCurrency(referenceAmount)
              })(
                <span>{currency}&nbsp;{common.formatCurrency(referenceAmount)}</span>
              )}
            </FormItem>
            <Row style={{marginBottom:'20px'}}>
              <Col span={6} style={{ textAlign:'right' }}>
                  <span className="valuation-detail" onMouseOver={this.handleMouseOver}
                        onMouseOut={this.handleMouseOut}>{messages('mileage-subsidy-expense.key14'/*查看计价明细*/)}
                  </span>
              </Col>
            </Row>
            {steps && <div style={{ display:display, marginBottom:'20px' }}>
              <div style={{ paddingLeft:'20px' }}>
                <Row>
                  <Col span={1}/>
                  <Col span={7} style={{textAlign:'center'}}>{messages('mileage-subsidy-expense.key15'/*里程数*/)}</Col>
                  <Col span={7} style={{textAlign:'center'}}>{messages('mileage-subsidy-expense.key16'/*单价/KM*/)}</Col>
                  <Col span={7} style={{textAlign:'center'}}>{messages('mileage-subsidy-expense.key8'/*金额*/)}</Col>
                </Row>
              </div>
              {steps.map((item,index) =>{
                return <Row key={item.startUnit} style={{paddingLeft:'20px'}}>
                  <Col span={1}/>
                  <Col span={7} style={{textAlign:'center'}}>{item.startUnit+'~'+item.endUnit}</Col>
                  <Col span={7} style={{textAlign:'center'}}>{item.unitPrice}</Col>
                  <Col span={7} style={{textAlign:'center'}}>{priceList[index]}</Col>
                </Row>
              })}
            </div>}
            <FormItem {...formItemLayout}  label={messages('mileage-subsidy-expense.key17'/*里程明细*/)}>
              {getFieldDecorator('mileageDetail')(
                <Table columns={columns}
                       dataSource={data}
                       bordered
                       size="middle"
                       loading={tableLoading}
                       onRow={record => ({onClick: () => this.handleRowClick(record)})}/>
              )}
            </FormItem>
            <FormItem {...formItemLayout}  label={messages('mileage-subsidy-expense.key6'/*事由说明*/)}>
              {getFieldDecorator('remark', {
                initialValue:remark
              })(
                <TextArea autosize={{ minRows: 4 }}
                          style={{ minWidth:'100%' }}
                          placeholder={messages('mileage-subsidy-expense.key18'/*请输入，最多输入200个汉字*/)}
                          maxLength="200"/>
              )}
            </FormItem>
            <Affix offsetBottom={0} className="bottom-bar">
              <Button onClick={this.goBack}>{messages('common.back')}</Button>
              <Button type="primary" htmlType="submit" disabled={true}>{messages('common.save')}</Button>
            </Affix>
          </Form>
          <Modal visible={visible}
                 title={messages('mileage-subsidy-expense.key17'/*里程明细*/)}
                 footer={[]}
                 onCancel={this.onCancel}>
            <Row><Col span={4}>{messages('mileage-subsidy-expense.key19'/*上车时间*/)}:</Col><Col span={20}>{record && moment(record.departTime).format('YYYY-MM-DD HH:mm')}</Col></Row>
            <Row><Col span={4}>{messages('mileage-subsidy-expense.key20'/*上车地点*/)}:</Col><Col span={20}>{record && record.start.place}</Col></Row>
            <Row><Col span={4}>{messages('mileage-subsidy-expense.key21'/*下车时间*/)}:</Col><Col span={20}>{record && moment(record.arriveTime).format('YYYY-MM-DD HH:mm')}</Col></Row>
            <Row><Col span={4}>{messages('mileage-subsidy-expense.key22'/*下车地点*/)}:</Col><Col span={20}>{record && record.end.place}</Col></Row>
            <Row><Col span={6}>{messages('mileage-subsidy-expense.key23'/*实际里程(KM)*/)}:</Col><Col span={18}>{record && record.mileage}</Col></Row>
            <Row><Col span={6}>{messages('mileage-subsidy-expense.key12'/*参考里程(KM)*/)}:</Col><Col span={18}>{record && record.referenceMileage}</Col></Row>
            <Row><Col span={4}>{messages('mileage-subsidy-expense.key6'/*事由说明*/)}:</Col><Col span={20}>{record && record.remark}</Col></Row>
          </Modal>
        </Spin>
      </div>
    )
  }
}
EditMileageCost.contextTypes = {
  router:React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    company: state.login.company
  }
}

const wrappedEditMileageCost = Form.create()(EditMileageCost)
export default connect(mapStateToProps)(wrappedEditMileageCost)
